import { createClient, Interceptor, ConnectError } from "@connectrpc/connect";
import type { Transport } from "@connectrpc/connect";
import { createGrpcWebTransport } from "@connectrpc/connect-web";
import { FormService } from "pb/proto/form/main_pb";
import { PageResponse , PageRequestSchema} from "pb/proto/form/getFormList_pb";
import { create } from "@bufbuild/protobuf";
import config from "bin/local.config"
import {CreateGroupRequestSchema, CreateGroupResponse} from "../../../pb/proto/form/createGroup_pb";
import {UpdateGroupRequestSchema, UpdateGroupResponse} from "../../../pb/proto/form/updateGroup_pb";
import {DeleteGroupRequestSchema, DeleteGroupResponse} from "../../../pb/proto/form/deleteGroup_pb";


const transport: Transport = createGrpcWebTransport({
    baseUrl: config.api.form.origin,
    useBinaryFormat: true,
    interceptors: [

    ]
})


const client = createClient(FormService, transport)
class FormApi {
    async getFormGroupList(name?: string): Promise<PageResponse> {
        // 使用 create() 函数和 Schema 创建请求对象
        const request = create(PageRequestSchema, {
            name: name || ""
        });

        // 发送请求
        return client.listForms(request);
    }


    async addFormGroup(groupData: { name: string; description: string; }): Promise<CreateGroupResponse> {
        const request = create(CreateGroupRequestSchema, {
            name: groupData.name,
            description: groupData.description
        });

        return client.createGroup(request);
    }


    async updateFormGroup(groupData: { id:string , name: string; description: string; }): Promise<UpdateGroupResponse> {
        const request = create(UpdateGroupRequestSchema, {
            id: groupData.id,
            name:groupData.name,
            description:groupData.description
        });

        return client.updateGroup(request);
    }

    async deleteFormGroup(groupData: { id:string , name: string; description: string; }): Promise<DeleteGroupResponse> {
        const request = create(DeleteGroupRequestSchema, {
            id: groupData.id,
        });

        return client.deleteGroup(request);
    }
}

export const formApi = new FormApi()
